﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.OrderSingleton;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Utilities;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DeHeng_Mes.PlcService
{
    public class ExitService
    {
        #region 成员实例
        OrderDao orderDao = new OrderDao();
        #endregion


        /// <summary>
        /// 执行出站
        /// </summary>
        /// <param name="station"></param>
        /// <returns></returns>
        public (int, List<int>) StationExit(string station, int index, byte[] bytes, List<string> codes, string operation, Model.ConfigModel.PlcOrderConfigModel orderModel)
        {
            // 初始化错误列表
            List<int> errorCodes = new List<int>();

            // 初始化NG状态列表
            List<bool> NgStatus = new List<bool>();

            DateTime now = DateTime.Now;

            int count = 0;

            try
            {
                foreach (var code in codes)
                {
                    if (station.Equals(SystemConstant.NgStationL) || station.Equals(SystemConstant.NgStationR))
                    {
                        // 记录NG工位出站
                        orderDao.NgStationSave(new NgStation()
                        {
                            CreateTime = now,
                            Station = station,
                            TraceId = code,
                            Status = "1"
                        });
                    }
                    else
                    {
                        string result = S7.Net.Types.Int.FromByteArray(bytes.Skip(index * 50 + 4).Take(2).ToArray()) == 1 ? "OK" : "NG";

                        Stopwatch stopwatch = Stopwatch.StartNew();
                        stopwatch.Start();
                        orderDao.UpdateStationEndTime(code, result, station, now, operation);
                        stopwatch.Stop();
                        long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                        Tools.ProduceLogTextError($"出站更新操作耗时[{elapsedMilliseconds}]MS");

                        // 产量更新
                        if (count == 0)
                            OrderProduction(station);
                    }

                    count++;
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"[{station}]触发出站失败，原因是[{ex.Message}]");

                errorCodes.Add(1506);

                return (1, errorCodes);
            }

            if (NgStatus.Count > 0) return (2, errorCodes);

            else return (1, errorCodes);
        }

        /// <summary>
        /// 当前存在工单时首工序产量统计
        /// </summary>
        /// <param name="station"></param>
        public void OrderProduction(string station)
        {
            if (!MappingTable.GetStartStation(station))
                return;

            OrderSingletonModel orderSingletonModel = OrderSingleton.Instance.Where(x => x.MaterialId.Equals(MappingTable.GetMaterialByStation(station))).FirstOrDefault();

            if (orderSingletonModel == null)
                return;

            orderDao.UpdateProduction(orderSingletonModel.OrderId);

            OrderSingleton.AddNumNow(orderSingletonModel.OrderId);
        }
    }
}
